"use client"

import { useState, useEffect } from "react"
import { Badge } from "@/components/ui/badge"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Calendar, ChevronLeft, ChevronRight, FileCheck, Download, Search } from "lucide-react"
import { Input } from "@/components/ui/input"
import { Button } from "@/components/ui/button"
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"
import { Calendar as CalendarComponent } from "@/components/ui/calendar"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog"
import { Label } from "@/components/ui/label"
import { format } from "date-fns"
import { apiClient } from "@/lib/api"
import { transformToGroupedData } from "@/lib/data-utils"
import type { SampleFilters, SampleGroup, BackendPaginatedResponse, ApiResponse, ExportRequest, Sample } from "@/types"

export default function CompletedRecordsPage() {
  const [groups, setGroups] = useState<SampleGroup[]>([])
  const [loading, setLoading] = useState(true)

  // 筛选和分页状态
  const [searchTerm, setSearchTerm] = useState("")
  const [startDate, setStartDate] = useState<Date | undefined>(undefined)
  const [endDate, setEndDate] = useState<Date | undefined>(undefined)
  const [currentPage, setCurrentPage] = useState(1)
  const [pageSize, setPageSize] = useState(10)
  const [totalGroups, setTotalGroups] = useState(0)
  const [totalPages, setTotalPages] = useState(0)
  const [totalSamples, setTotalSamples] = useState(0)

  // 导出对话框状态
  const [showExportDialog, setShowExportDialog] = useState(false)
  const [exportStartDate, setExportStartDate] = useState<Date | undefined>(undefined)
  const [exportEndDate, setExportEndDate] = useState<Date | undefined>(undefined)
  const [exportFormat, setExportFormat] = useState<"excel" | "pdf">("excel")
  const [isExporting, setIsExporting] = useState(false)

  // 统计数据
  const [stats, setStats] = useState({
    samplingGroups: 0,
    completedSamples: 0,
    totalProcessingTime: 0,
  })

  // 获取已完成的样品数据
  const fetchSamples = async () => {
    setLoading(true)
    try {
      const filters: SampleFilters = {
        search: searchTerm,
        status: "complete", // 修正为接口定义的正确值
        startDate: startDate?.toISOString(),
        endDate: endDate?.toISOString(),
        page: currentPage,
        pageSize: pageSize,
      }

      const queryParams = new URLSearchParams()
      Object.entries(filters).forEach(([key, value]) => {
        if (value !== undefined && value !== null && value !== "") {
          queryParams.append(key, value.toString())
        }
      })

      const result: ApiResponse<BackendPaginatedResponse<Sample>> = await apiClient.get(`/samples?${queryParams}`)

      if (result.success && result.data) {
        const backendData = result.data

        // 转换为前端分组格式
        const transformedData = transformToGroupedData(backendData, "completed")

        setGroups(transformedData.groups)
        setTotalGroups(transformedData.total)
        setTotalPages(transformedData.totalPages)
        setTotalSamples(transformedData.totalSamples)
      }
    } catch (error) {
      console.error("获取样品数据失败:", error)
    } finally {
      setLoading(false)
    }
  }

  // 获取统计数据
  const fetchStats = async () => {
    try {
      // 注意：这里应该定义具体的StatsResponse类型，暂时使用any
      const result: ApiResponse<any> = await apiClient.get("/samples/stats")
      if (result.success && result.data) {
        setStats({
          samplingGroups: result.data.samplingGroups,
          completedSamples: result.data.total - result.data.unassigned - result.data.mixedOnly,
          totalProcessingTime: 0,
        })
      }
    } catch (error) {
      console.error("获取统计数据失败:", error)
    }
  }

  useEffect(() => {
    fetchSamples()
  }, [currentPage, pageSize, searchTerm, startDate, endDate])

  useEffect(() => {
    fetchStats()
  }, [])

  const getMixedNumberColor = (mixedNumber: string) => {
    const colors = [
      "bg-blue-100 text-blue-800",
      "bg-green-100 text-green-800",
      "bg-purple-100 text-purple-800",
      "bg-orange-100 text-orange-800",
    ]
    const index = Number.parseInt(mixedNumber.replace("MX", "")) % colors.length
    return colors[index]
  }

  const getSamplingNumberColor = (samplingNumber: string) => {
    const colors = ["bg-red-100 text-red-800", "bg-indigo-100 text-indigo-800", "bg-pink-100 text-pink-800"]
    const index = Number.parseInt(samplingNumber.replace("SP", "")) % colors.length
    return colors[index]
  }

  const getMixedCellBorderStyle = (mixedNumber: string) => {
    const baseStyle = "border-l-4"
    const colors = ["border-blue-300", "border-green-300", "border-purple-300", "border-orange-300"]
    const index = Number.parseInt(mixedNumber.replace("MX", "")) % colors.length
    return `${baseStyle} ${colors[index]}`
  }

  // 导出数据
  const handleExport = async () => {
    if (!exportStartDate || !exportEndDate) {
      alert("请选择导出时间范围")
      return
    }

    if (exportStartDate > exportEndDate) {
      alert("开始日期不能晚于结束日期")
      return
    }

    setIsExporting(true)
    try {
      const exportData: ExportRequest = {
        startDate: exportStartDate.toISOString().split("T")[0], // 只取日期部分
        endDate: exportEndDate.toISOString().split("T")[0],
        status: "complete",
        format: exportFormat,
      }

      const queryParams = new URLSearchParams(exportData as any)
      const filename = `样品处理完成记录_${exportData.startDate}_${exportData.endDate}.${exportFormat === "excel" ? "xlsx" : "pdf"}`

      await apiClient.downloadFile(`/samples/export?${queryParams}`, filename)

      setShowExportDialog(false)
      alert("导出成功！")
    } catch (error) {
      alert("导出失败，请稍后重试")
    } finally {
      setIsExporting(false)
    }
  }

  return (
      <div className="p-6 space-y-6">
        {/* 页面标题 */}
        <div className="flex justify-between items-center">
          <div>
            <h1 className="text-2xl font-bold flex items-center gap-2">
              <FileCheck className="h-7 w-7 text-purple-600" />
              处理完成记录
            </h1>
            <p className="text-muted-foreground">查看已完成混样和抽检编号分配的样品处理记录</p>
          </div>
          <Dialog open={showExportDialog} onOpenChange={setShowExportDialog}>
            <DialogTrigger asChild>
              <Button className="bg-purple-600 hover:bg-purple-700">
                <Download className="w-4 h-4 mr-2" />
                导出记录
              </Button>
            </DialogTrigger>
            <DialogContent>
              <DialogHeader>
                <DialogTitle>导出处理完成记录</DialogTitle>
              </DialogHeader>
              <div className="space-y-4">
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <Label>开始日期</Label>
                    <div className="mt-1">
                      <Popover>
                        <PopoverTrigger asChild>
                          <Button variant="outline" className="w-full justify-start bg-transparent">
                            <Calendar className="mr-2 h-4 w-4" />
                            {exportStartDate ? format(exportStartDate, "yyyy-MM-dd") : "选择开始日期"}
                          </Button>
                        </PopoverTrigger>
                        <PopoverContent className="w-auto p-0">
                          <CalendarComponent mode="single" selected={exportStartDate} onSelect={setExportStartDate} />
                        </PopoverContent>
                      </Popover>
                    </div>
                  </div>
                  <div>
                    <Label>结束日期</Label>
                    <div className="mt-1">
                      <Popover>
                        <PopoverTrigger asChild>
                          <Button variant="outline" className="w-full justify-start bg-transparent">
                            <Calendar className="mr-2 h-4 w-4" />
                            {exportEndDate ? format(exportEndDate, "yyyy-MM-dd") : "选择结束日期"}
                          </Button>
                        </PopoverTrigger>
                        <PopoverContent className="w-auto p-0">
                          <CalendarComponent mode="single" selected={exportEndDate} onSelect={setExportEndDate} />
                        </PopoverContent>
                      </Popover>
                    </div>
                  </div>
                </div>
                <div>
                  <Label>导出格式</Label>
                  <Select value={exportFormat} onValueChange={(value: "excel" | "pdf") => setExportFormat(value)}>
                    <SelectTrigger className="mt-1">
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="excel">Excel (.xlsx)</SelectItem>
                      <SelectItem value="pdf">PDF (.pdf)</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
                <div className="bg-blue-50 p-3 rounded-lg text-sm">
                  <strong>导出说明：</strong>
                  <ul className="mt-2 space-y-1 text-muted-foreground">
                    <li>• 导出时间范围以天为维度，包含选定日期内的所有记录</li>
                    <li>• Excel格式便于数据分析和进一步处理</li>
                    <li>• PDF格式适合打印和存档</li>
                  </ul>
                </div>
                <div className="flex justify-end gap-2">
                  <Button variant="outline" onClick={() => setShowExportDialog(false)}>
                    取消
                  </Button>
                  <Button
                      onClick={handleExport}
                      disabled={isExporting || !exportStartDate || !exportEndDate}
                      className="bg-purple-600 hover:bg-purple-700"
                  >
                    {isExporting ? "导出中..." : "确认导出"}
                  </Button>
                </div>
              </div>
            </DialogContent>
          </Dialog>
        </div>

        {/* 搜索和筛选条件 */}
        <div className="flex gap-4 items-center flex-wrap">
          <div className="relative">
            <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground" />
            <Input
                placeholder="搜索样品编号、名称、编号..."
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                className="w-64 pl-10"
            />
          </div>

          <Popover>
            <PopoverTrigger asChild>
              <Button variant="outline" size="icon">
                <Calendar className="h-4 w-4" />
              </Button>
            </PopoverTrigger>
            <PopoverContent className="w-auto p-0" align="end">
              <div className="p-3 border-b">
                <div className="text-sm font-medium">完成时间范围</div>
              </div>
              <div className="p-3 flex flex-col gap-2">
                <div>
                  <div className="text-xs mb-1">开始日期</div>
                  <CalendarComponent
                      mode="single"
                      selected={startDate}
                      onSelect={setStartDate}
                      className="border rounded-md"
                  />
                </div>
                <div>
                  <div className="text-xs mb-1">结束日期</div>
                  <CalendarComponent
                      mode="single"
                      selected={endDate}
                      onSelect={setEndDate}
                      className="border rounded-md"
                  />
                </div>
                <div className="flex justify-end">
                  <Button
                      variant="outline"
                      size="sm"
                      onClick={() => {
                        setStartDate(undefined)
                        setEndDate(undefined)
                      }}
                  >
                    重置
                  </Button>
                </div>
              </div>
            </PopoverContent>
          </Popover>

          <Select value={pageSize.toString()} onValueChange={(value) => setPageSize(Number(value))}>
            <SelectTrigger className="w-32">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="5">5组/页</SelectItem>
              <SelectItem value="10">10组/页</SelectItem>
              <SelectItem value="20">20组/页</SelectItem>
              <SelectItem value="50">50组/页</SelectItem>
            </SelectContent>
          </Select>
        </div>

        {/* 样品表格 */}
        <Card>
          <CardContent className="p-0">
            {loading ? (
                <div className="flex items-center justify-center h-64">
                  <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-purple-600"></div>
                </div>
            ) : totalSamples === 0 ? (
                <div className="flex flex-col items-center justify-center h-64 text-muted-foreground">
                  <FileCheck className="h-12 w-12 mb-4" />
                  <p className="text-lg font-medium">暂无完成记录</p>
                  <p className="text-sm">还没有样品完成完整的处理流程</p>
                </div>
            ) : (
                <>
                  <Table>
                    <TableHeader>
                      <TableRow className="bg-gray-100">
                        <TableHead>抽检编号</TableHead>
                        <TableHead>混样编号</TableHead>
                        <TableHead>样品编号</TableHead>
                        <TableHead>样品名称</TableHead>
                        <TableHead>样品类型</TableHead>
                        <TableHead>送检单位</TableHead>
                        <TableHead>操作人</TableHead>
                        <TableHead>完成时间</TableHead>
                      </TableRow>
                    </TableHeader>
                    <TableBody>
                      {groups.map((group) => {
                        const samplingNumber = group.samplingNumber!

                        // 按混合编号分组显示
                        const mixedGroups = new Map<string, any[]>()
                        group.samples.forEach((sample) => {
                          const mixedNum = sample.mixedNumber!
                          if (!mixedGroups.has(mixedNum)) {
                            mixedGroups.set(mixedNum, [])
                          }
                          mixedGroups.get(mixedNum)!.push(sample)
                        })

                        let isFirstSamplingRow = true
                        return Array.from(mixedGroups.entries()).map(([mixedNumber, samples]) =>
                            samples.map((sample, sampleIndex) => {
                              const showSamplingCell = isFirstSamplingRow
                              const showMixedCell = sampleIndex === 0

                              const row = (
                                  <TableRow key={sample.id} className="bg-green-50 hover:bg-green-100">
                                    {showSamplingCell && (
                                        <TableCell
                                            rowSpan={group.samples.length}
                                            className="align-middle border-l-4 border-green-300"
                                        >
                                          <Badge variant="secondary" className={getSamplingNumberColor(samplingNumber)}>
                                            {samplingNumber}
                                          </Badge>
                                        </TableCell>
                                    )}
                                    {showMixedCell && (
                                        <TableCell
                                            rowSpan={samples.length}
                                            className={`align-middle ${getMixedCellBorderStyle(mixedNumber)}`}
                                        >
                                          <Badge variant="secondary" className={getMixedNumberColor(mixedNumber)}>
                                            {mixedNumber}
                                          </Badge>
                                        </TableCell>
                                    )}
                                    <TableCell className="font-mono text-sm">{sample.sampleNumber}</TableCell>
                                    <TableCell>{sample.sampleName}</TableCell>
                                    <TableCell>{sample.sampleType}</TableCell>
                                    <TableCell>{sample.testingUnit}</TableCell>
                                    <TableCell>{sample.operator}</TableCell>
                                    <TableCell>
                                      {sample.operationTime ? format(new Date(sample.operationTime), "yyyy-MM-dd HH:mm") : "-"}
                                    </TableCell>
                                  </TableRow>
                              )

                              if (showSamplingCell) isFirstSamplingRow = false
                              return row
                            }),
                        )
                      })}
                    </TableBody>
                  </Table>

                  {/* 分页控件 */}
                  <div className="flex items-center justify-between px-6 py-4 border-t">
                    <div className="text-sm text-muted-foreground">
                      显示第 {(currentPage - 1) * pageSize + 1} - {Math.min(currentPage * pageSize, totalGroups)} 组，共{" "}
                      {totalGroups} 个抽检组 ({totalSamples} 个样品)
                    </div>
                    <div className="flex items-center gap-2">
                      <Button
                          variant="outline"
                          size="sm"
                          onClick={() => setCurrentPage(Math.max(1, currentPage - 1))}
                          disabled={currentPage === 1}
                      >
                        <ChevronLeft className="h-4 w-4" />
                        上一页
                      </Button>
                      <div className="flex items-center gap-1">
                        {Array.from({ length: Math.min(5, totalPages) }, (_, i) => {
                          let pageNum
                          if (totalPages <= 5) {
                            pageNum = i + 1
                          } else if (currentPage <= 3) {
                            pageNum = i + 1
                          } else if (currentPage >= totalPages - 2) {
                            pageNum = totalPages - 4 + i
                          } else {
                            pageNum = currentPage - 2 + i
                          }

                          return (
                              <Button
                                  key={pageNum}
                                  variant={currentPage === pageNum ? "default" : "outline"}
                                  size="sm"
                                  onClick={() => setCurrentPage(pageNum)}
                                  className="w-8 h-8 p-0"
                              >
                                {pageNum}
                              </Button>
                          )
                        })}
                      </div>
                      <Button
                          variant="outline"
                          size="sm"
                          onClick={() => setCurrentPage(Math.min(totalPages, currentPage + 1))}
                          disabled={currentPage === totalPages}
                      >
                        下一页
                        <ChevronRight className="h-4 w-4" />
                      </Button>
                    </div>
                  </div>
                </>
            )}
          </CardContent>
        </Card>

        {/* 记录说明 */}
        <Card>
          <CardContent className="p-4">
            <div className="text-sm space-y-2">
              <div>
                <strong>处理完成记录说明：</strong>
              </div>
              <ul className="list-disc list-inside space-y-1 text-muted-foreground">
                <li>此页面显示已完成混样和抽检编号分配的所有样品记录</li>
                <li>每个样品都具有完整的编号体系：样品编号 → 混样编号 → 抽检编号</li>
                <li>记录按抽检编号分组显示，便于质量追溯和管理</li>
                <li>可以通过搜索功能快速查找特定的样品或编号</li>
                <li>支持按时间范围筛选和数据导出功能</li>
              </ul>
            </div>
          </CardContent>
        </Card>
      </div>
  )
}
